package web

import (
	"io/fs"
	"net/http"

	"github.com/gin-gonic/gin"
)

// setupIndexRoutes 设置首页相关路由(适配VUE打包结构)
func (s *Server) setupIndexRoutes(router *gin.Engine) {
	// 获取 embed.FS
	fsys := StaticHandler()

	// 1. 挂载 /assets 路由
	assetsFS, err := fs.Sub(fsys, "assets")
	if err != nil {
		panic("assets 目录不存在")
	}
	router.StaticFS("/assets", http.FS(assetsFS))

	// 2. 首页和前端 history 路由支持
	router.GET("/", func(c *gin.Context) {
		file, err := fsys.Open("index.html")
		if err != nil {
			c.String(http.StatusInternalServerError, "index.html not found")
			return
		}
		defer file.Close()
		stat, _ := file.Stat()
		c.DataFromReader(http.StatusOK, stat.Size(), "text/html; charset=utf-8", file, nil)
	})

	router.NoRoute(func(c *gin.Context) {
		// 检查是否是API请求
		if c.Request.URL.Path == "/api/v2/detect" {
			c.JSON(http.StatusNotFound, gin.H{
				"error": "Not Found",
			})
			return
		}
		// 返回 index.html
		file, err := fsys.Open("index.html")
		if err != nil {
			c.String(http.StatusInternalServerError, "index.html not found")
			return
		}
		defer file.Close()
		stat, _ := file.Stat()
		c.DataFromReader(http.StatusOK, stat.Size(), "text/html; charset=utf-8", file, nil)
	})
}
